package event.gui;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JComponent;
import javax.swing.Timer;

import main.gui.NarwhalImage;
import main.model.Settings;
import event.model.NarwhalEvent;

@SuppressWarnings("serial")
public class EventFrame extends JComponent implements ActionListener, Observer {

	private static final int TIME_UNTILL_STANDBY = 300000;
	private final int EXPAND = -1;
	private final int COLLAPSE = 1;
	private final int DO_NOTHING = 0;

	private EventSideButton active;
	private EventInfoScreen info;
	private int toDo = 0;
	private Timer timer;
	private NarwhalEvent model;
	private LinkedList<EventSideButton> buttons;

	public EventFrame(NarwhalEvent model) {
		timer = new Timer(TIME_UNTILL_STANDBY, this);
		this.model = model;
		buttons = new LinkedList<EventSideButton>();

		setLayout(null);
		info = new EventInfoScreen(model, this);
		info.setBounds(320, 10, 694, 20);
		add(info);

		updateButtons();

		NarwhalImage dLogo = new NarwhalImage("dLogo.png");
		dLogo.setBounds(500, 330, 800, 800);
		add(dLogo);
		
		NarwhalImage cLogo = new NarwhalImage("cLogo.png");
		cLogo.setBounds(-200, 500, 450, 450);
		add(cLogo);

		model.addObserver(this);
	}

	public void trigger() {
		if (toDo == DO_NOTHING)
			return;
		if (toDo == COLLAPSE)
			info.collapse();
		else
			info.expand();
		toDo = DO_NOTHING;
	}

	public void setActive(EventSideButton b) {
		if (!info.isEnabled())
			return;
		if (b == active) {
			info.collapse();
			b.setActive(false);
			active = null;
			return;
		}
		model.setActive(b.getIndex());
		toDo = EXPAND;
		info.collapse();
		if (active != null)
			active.setActive(false);
		b.setActive(true);
		active = b;
		timer.restart();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		info.collapse();
		if (active != null)
			active.setActive(false);
		active = null;
		timer.stop();
	}

	@Override
	public void update(Observable o, Object arg) {
		updateButtons();
	}

	public void updateButtons() {
		for (EventSideButton b : buttons) {
			remove(b);
		}
		ArrayList<Integer> list = model.getEventIndexes();
		for (int i = 0; i < list.size(); i++) {
			EventSideButton b = new EventSideButton(model, this, list.get(i));
			b.setBounds(10, 70 * i + 10, 300, 50);
			buttons.add(b);
			
			if (b.equals(active)) {
				b.setActive(true);
				active = b;
			}
			add(b);
			setComponentZOrder(b, 0);
		}
		repaint();
	}

	public void moveMouse() {
		if (!new Settings().moveMouse())
			return;
		try {
			Robot r = new Robot();
			r.mouseMove(0, 0);
		} catch (AWTException e) {
			System.err.println("Tried to move mouse!");
			e.printStackTrace();
		}
	}
}
